<?php

class TweetController extends Controller {
    
    public function actionIndex() {
        $this->layout='//layouts/home';
        $this->render('index');
    }
    
    public function actionUser() {
        $this->layout='//layouts/user';
        $this->render('user');
    }
    
    public function filters() {
        return array(
            'accessControl',
        );
    }
    
    public function accessRules() {
        return array(
            array('allow', // allow authenticated users to access all actions　　（　されたユーザーはすべてのアクションへのアクセスを許可する　）
                'users' => array('@'),
            ),
            array('deny', // deny all users　(すべてのユーザーを拒否する。)
                'users' => array('*'),
            ),
        );
    }
    
    // TODO
    public function actionFollow()
    {
        $user_id = yii::app()->user->id;
    }
    
    /**
     * Perform action when user favor a tweet
     * @param int $tweet_id the id of be favor tweet
     */
    public function actionFavorite ($tweet_id)
    {
        $user_id = yii::app()->user->id;
        
        echo $user_id;
        echo "<br>";
        echo $tweet_id;
        
        $refav = Refavs::model()->findByAttributes(array('tweet_id' => $tweet_id, 'user_id' => $user_id));
        
        if ($refav)     // If record exist
        {
            switch ($refav->refav)
            {
                case Refavs::NONE:
                    $refav->refav = Refavs::FAVORITED;
                    // Save the record
                    if ($refav->save()) 
                    {
                        echo "<br>OK";
                    }
                    break;
                case Refavs::RETWEETED:
                    $refav->refav = Refavs::REFAV;
                    // Save the record
                    if ($refav->save()) 
                    {
                        echo "<br>OK";
                    }
                    break;
            }
        }
        
        
        else // If record not exist
        {
            $refav = new Refavs();
            $refav->tweet_id = $tweet_id;
            $refav->user_id = $user_id;
            $refav->refav = Refavs::FAVORITE;
            
            // Save the record
            if ($refav->save())
            {
                echo "<br>OK";
            }
        }
    }
}